package legoproject;

import java.io.IOException;

import lejos.nxt.*;
import lejos.nxt.comm.*;
import java.io.*;
import javax.bluetooth.*;

/**
 * Manager som GarbageCollector klassen har en instans af som kan benyttes til at tilgaa sensorer og motore paa slave
 */
public class BluetoothManager {

    private String name = "Slave";
    private RemoteDevice btrd;
    private BTConnection btc;
    private DataInputStream dis;
    private DataOutputStream dos;

    public void init() {
        btrd = Bluetooth.getKnownDevice(name);

        if (btrd == null) {
            GarbageCollector.reporter.error(1);
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
            }
            System.exit(1);
        }

        btc = Bluetooth.connect(btrd);

        if (btc == null) {
            GarbageCollector.reporter.error(2);
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
            }
            System.exit(1);
        }

        dis = btc.openDataInputStream();
        dos = btc.openDataOutputStream();

    }

    public int sendCommand(int command) throws Exception {
        int result = -1;
        GarbageCollector.reporter.sendingBTCommand(command);
        try {
            dos.writeInt(command);
            dos.flush();
            result = dis.readInt();

        } catch (IOException ioe) {
            GarbageCollector.reporter.error(3);
        }

        return result;
    }
}


